package com.xkxbx.kkk.dyw;

import android.annotation.SuppressLint;
import android.content.pm.ActivityInfo;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;

import com.console.game.common.sdk.core.CommonSDKApiCallBack;
import com.console.game.common.sdk.core.CommonSDKGameGradingCallBack;
import com.console.game.common.sdk.core.CommonSDKManager;
import com.console.game.common.sdk.entity.CommonInitBean;
import com.console.game.common.sdk.entity.CommonRoleBean;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends FragmentActivity {

  NetWorkStateReceiver netWorkStateReceiver;

  public TWebView webView;

  private static final String TAG = MainActivity.class.getSimpleName();

  public static String uuid;
  public static String sign;
  public static String age;

  @SuppressLint("JavascriptInterface")
  @Override
  protected void onCreate(Bundle savedInstanceState) {
//    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
//            .detectDiskReads()
//            .detectDiskWrites()
//            .detectNetwork()
//            .penaltyLog()
//            .build());
//    StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
//            .detectLeakedSqlLiteObjects()
//            .detectLeakedClosableObjects()
//            .penaltyLog()
////            .penaltyDeath()
//            .build());

    super.onCreate(savedInstanceState);

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    setContentView(R.layout.activity_main);
    WebView.setWebContentsDebuggingEnabled(true);

    this.hideVirtualButton();

    CommonSDKManager.newInstance().onCreate(this);
    CommonInitBean initBean = new CommonInitBean();
    initBean.setOrientation(1);

    CommonSDKManager.newInstance().initSdk(this, initBean, new CommonSDKApiCallBack() {
          @Override
          public void initFinish(String json) {
//            Log.d(TAG, "initFinish");
//            Toast.makeText(MainActivity.this, "初始化完成", Toast.LENGTH_SHORT).show();
            login(json);
          }

          @Override
          public void payComplete(String json) {
            try {
              Log.d(TAG, "payComplete:" + json);
              JSONObject jsonObject = new JSONObject(json);
              //          orderId = jsonObject.optString("order_id");
              //          if (et_order_id != null && !TextUtils.isEmpty(orderId)) {
              //            et_order_id.setText(orderId);
              //          }
              //          secretCode = jsonObject.optString("secret_code");
              //          if (et_supply_order_id != null && !TextUtils.isEmpty(secretCode)) {
              //            et_supply_order_id.setText(secretCode);
              //          }
            } catch (JSONException e) {
              Log.e(TAG,"payComplete:" + e);
            }
          }

          @Override
          public void rebateComplete(String json) {
            Log.d(TAG,"rebateComplete = " + json);
//            Toast.makeText(MainActivity.this, json, Toast.LENGTH_SHORT).show();
          }

          @Override
          public void changeAccount(String json) {
//            Log.d(TAG,"changeAccount = " + json);
//            Toast.makeText(MainActivity.this, "切换账号", Toast.LENGTH_SHORT).show();
            login(json);
          }

          @Override
          public void shareSuccess(String json) {
            Log.d(TAG,"shareSuccess = " + json);
//            Toast.makeText(MainActivity.this, "分享成功，发放奖励", Toast.LENGTH_SHORT).show();
          }

          @Override
          public void exchangeGift(String json) {
            if (null != webView){
              webView.evaluateJavascript("javascript:exchangeGift('"+json+"')", null);
            }
          }

          @Override
          public void adAwardSuccess(String json) {
            Log.d(TAG,"看完广告，可以发放奖励");
//            Toast.makeText(MainActivity.this, "看完广告，可以发放奖励", Toast.LENGTH_SHORT).show();
          }

          @Override
          public void payHistory(String json) {}
        }
      );

    CommonSDKManager.newInstance().fetchGameGrading(this, new CommonSDKGameGradingCallBack() {
      @Override
      public void finish(boolean isVisible, int gameGrading) {
        if (isVisible) {// 展示适龄图标
//          iv_game_grading.setVisibility(View.VISIBLE);
          // 游戏适龄提示年龄类型，1代表 8+； 2代表 12+ ； 3代表16+
          if (gameGrading == 1) {
//            iv_game_grading.setImageResource(R.drawable.game_grading_8);
          } else if (gameGrading == 2) {
//            iv_game_grading.setImageResource(R.drawable.game_grading_12);
          } else if (gameGrading == 3) {
//            iv_game_grading.setImageResource(R.drawable.game_grading_16);
          }
        } else {// 隐藏适龄图标
//          iv_game_grading.setVisibility(View.GONE);
        }
      }
    });

    int x = ViewGroup.LayoutParams.MATCH_PARENT;
    int y = ViewGroup.LayoutParams.MATCH_PARENT;
    ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(x, y);

    TWebView webView = new TWebView(this);
    webView.isLoad = false;
    this.webView = webView;
    this.addContentView(webView, params);

    String url = BuildConfig.APP_URL;
    webView.loadUrl(url);
    Log.e(TAG,"loadUrl:" + url);

    //②将object对象暴露给Js,调用addJavascriptInterface
    webView.addJavascriptInterface(this, "ANDROID");
  }

  protected void login(final String json) {
    try {
      JSONObject jsonObject = new JSONObject(json);
      final JSONObject data = jsonObject.getJSONObject("data");
      MainActivity.uuid = data.getString("uuid");
      MainActivity.sign = data.getString("sign");

      final String user_id = data.getString("user_id");
      final String timestamp = data.getString("timestamp");

      final String outMd5 = Md5.encodeByMD5("ac=queryAge&ct=cp_user&time="+timestamp);

      new Thread(new Runnable() {
        @Override
        public void run() {
          String ageData = HttpRequest.sendRequest("https://rhapi.3kapi.com"+"?time="+timestamp+"&sign="+outMd5+"&ct=cp_user&ac=queryAge&user_id="+user_id,"GET");
          try {
            JSONObject ageDataObject = new JSONObject(ageData);
            JSONObject ageJson = ageDataObject.getJSONObject("data");
            MainActivity.age = ageJson.getString("age");
//            Log.d(TAG, "age= "+MainActivity.age);
          } catch (JSONException e) {
            Log.e(TAG,"Thread" + e);
          }
        }
      }).start();

    } catch (JSONException e) {
      Log.e(TAG,"" + e);
    }
  }

  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    CommonSDKManager.newInstance().onRequestPermissionsResult(this, requestCode, permissions, grantResults);
  }

  @Override
  protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    CommonSDKManager.newInstance().onNewIntent(this, intent);
  }

  @Override
  protected void onRestart() {
    super.onRestart();
    CommonSDKManager.newInstance().onReStart(this);
  }

  @Override
  protected void onStart() {
    super.onStart();
    CommonSDKManager.newInstance().onStart(this);
  }

  @Override
  protected void onResume() {
    if (netWorkStateReceiver == null) {
      netWorkStateReceiver = new NetWorkStateReceiver();
      netWorkStateReceiver.webView = this.webView;
    }
    IntentFilter filter = new IntentFilter();
    filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(netWorkStateReceiver, filter);
    Log.e(TAG,"注册" );
    super.onResume();
    CommonSDKManager.newInstance().onResume(this);
    this.hideVirtualButton();
  }

  @Override
  protected void onPause() {
    unregisterReceiver(netWorkStateReceiver);
    Log.e(TAG,"注销" );
    super.onPause();
    CommonSDKManager.newInstance().onPause(this);
  }

  @Override
  protected void onStop() {
    super.onStop();
    CommonSDKManager.newInstance().onStop(this);
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    CommonSDKManager.newInstance().onDestroy(this);
  }

  //进入登陆
  @JavascriptInterface
  public void setIsLoad() {
    this.webView.isLoad = true;
  }

  //获取渠道ID,如果返回值为3或17，请展示该接口按钮，否则屏蔽该入口按钮
  @JavascriptInterface
  public int getChannelSDKID() {
    return CommonSDKManager.newInstance().getChannelSDKID(this);
  }

  //显示SDK主界面
  @JavascriptInterface
  public void showMain() {
    CommonSDKManager.newInstance().showMain(this);
  }

  //账号管理接口
  @JavascriptInterface
  public void showAccountManager() {
    CommonSDKManager.newInstance().showAccountManager(this);
  }

  //打开FAQS系统接口
  @JavascriptInterface
  public void showFAQS() {
    CommonSDKManager.newInstance().showFAQS(this);
  }

  //打开适龄提醒详情接口
  @JavascriptInterface
  public void showGameGradingDetail() {
    CommonSDKManager.newInstance().showGameGradingDetail(this);
  }

  //打开隐私政策接口
  @JavascriptInterface
  public void showPrivacyPolicy() {
    CommonSDKManager.newInstance().showPrivacyPolicy(this);
  }

  //兑换礼包接口
  @JavascriptInterface
  public void useGift(String giftCode) {
    CommonSDKManager.newInstance().useGift(this,  giftCode);
  }

  //上报角色信息接口
  @JavascriptInterface
  public void sendRole(String serverId,String roleName,String roleLevel,String balance,int type) {
    CommonRoleBean roleInfo = new CommonRoleBean();
    roleInfo.setServerId(serverId);
    String userId = CommonSDKManager.newInstance().getUserId(this);
    roleInfo.setRoleId(userId);
    roleInfo.setRoleName(roleName);
    roleInfo.setRoleLevel(roleLevel);
    roleInfo.setBalance(balance);
    roleInfo.setType(type);
    CommonSDKManager.newInstance().role(this,roleInfo);
  }

  @JavascriptInterface
  public String getUserId() {
    String userId = CommonSDKManager.newInstance().getUserId(this);
    return userId;
  }

  @JavascriptInterface
  public String getLoginInfo() {
    String str = uuid+"|"+sign;
    return str;
  }

  @JavascriptInterface
  public String getUserAge() { return age; }

  //游戏事件打点接口
  @JavascriptInterface
  public void eventUpload(String eventName,String[] ext) {
    CommonSDKManager.newInstance().eventUpload(this,eventName,ext);
  }

  //第一次点击事件发生的时间
  private long mExitTime;

  /**
   * 点击两次返回退出app
   */
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
      boolean result = CommonSDKManager.newInstance().showExitView(this);
      if (!result){
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
          Toast.makeText(this, "再按一次退出游戏", Toast.LENGTH_SHORT).show();
          mExitTime = System.currentTimeMillis();
        } else {
          finish();
          System.exit(0);
        }
      }
      return true;
    }
    return super.onKeyDown(keyCode, event);
  }

  protected void hideVirtualButton() {
    if (Build.VERSION.SDK_INT >= 19) {
      // use reflection to remove dependence of API level

      Class viewClass = View.class;

      try {
        final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = Cocos2dxReflectionHelper.<Integer>getConstantValue(
          viewClass,
          "SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION"
        );
        final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = Cocos2dxReflectionHelper.<Integer>getConstantValue(
          viewClass,
          "SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN"
        );
        final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = Cocos2dxReflectionHelper.<Integer>getConstantValue(
          viewClass,
          "SYSTEM_UI_FLAG_HIDE_NAVIGATION"
        );
        final int SYSTEM_UI_FLAG_FULLSCREEN = Cocos2dxReflectionHelper.<Integer>getConstantValue(
          viewClass,
          "SYSTEM_UI_FLAG_FULLSCREEN"
        );
        final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = Cocos2dxReflectionHelper.<Integer>getConstantValue(
          viewClass,
          "SYSTEM_UI_FLAG_IMMERSIVE_STICKY"
        );
        final int SYSTEM_UI_FLAG_LAYOUT_STABLE = Cocos2dxReflectionHelper.<Integer>getConstantValue(
          viewClass,
          "SYSTEM_UI_FLAG_LAYOUT_STABLE"
        );

        // getWindow().getDecorView().setSystemUiVisibility();
        final Object[] parameters = new Object[] {
          //                        SYSTEM_UI_FLAG_LAYOUT_STABLE |
          //                         SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
          //                         SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
          SYSTEM_UI_FLAG_HIDE_NAVIGATION | // hide nav bar
          //                        SYSTEM_UI_FLAG_FULLSCREEN |// hide status bar
          SYSTEM_UI_FLAG_IMMERSIVE_STICKY,
        };
        Cocos2dxReflectionHelper.<Void>invokeInstanceMethod(
          getWindow().getDecorView(),
          "setSystemUiVisibility",
          new Class[] { Integer.TYPE },
          parameters
        );
      } catch (NullPointerException e) {
        Log.e(TAG, "hideVirtualButton", e);
      }
    }
  }
}
